package com.itheima.controller;

import com.itheima.common.R;
import io.swagger.annotations.Api;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Api(tags = "文件上传下载相关接口")
public class CommonController {

    @Value("${reggie.filepath}")
    private String path;


    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            response.setContentType("image/jpeg");
            FileInputStream fileInputStream =
                    new FileInputStream(new File(path,name));
            ServletOutputStream outputStream = response.getOutputStream();
            IOUtils.copy(fileInputStream,outputStream);
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/upload")
    public R upload(MultipartFile file){
        // 文件名： uuid作为文件名
        String fileName = UUID.randomUUID().toString();
        // 获取文件后缀名
        // 获取原始文件名 user.jpg
        String originalFilename = file.getOriginalFilename();
        // 字符串截取 .jpg
        String suffixName =
                originalFilename.substring(originalFilename.lastIndexOf("."));
        //判断文件夹是否存在，不存在则创建 path: d:\image
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }

        //将文件存储到指定的位置
        try {
            file.transferTo(new File(path,fileName+suffixName));
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("出错啦，稍后重试！！");
        }
        return R.success(fileName+suffixName);
    }
}
